<template>
    <view class="question">
        <view v-for="(item, index) in questions" class="question__item">
            <input :value="item" placeholder="请输入您的问题" class="question__input" @input="handleInput($event,index)"
            />
            <view @click="handleDel(index)" class="question__del">删除</view>
        </view>
        <view @click="handleAdd" class="question__button">添加问题</view>
        <view @click="handleSave" class="question__button question__save">保存</view>
    </view>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { CacheQuestion } from '@/utils/cache'
import navigator from '@/utils/navigator'
import { fetchData } from './service'

const questions = ref<Array<string>>([])

const handleInput = (event, idx) => {
    questions.value[idx] = event.detail.value
}
const handleAdd = () => {
    questions.value.push('')
}
const handleDel = (idx) => {
    uni.showModal({
        title: '提示',
        content: '是否删除当前问题?',
        showCancel: true,
        success: ({ confirm, cancel }) => {
            if(confirm) {
                questions.value.splice(idx, 1)
            }
        }
    })
    
}
const handleSave = () => {
    const result = questions.value.filter(Boolean)
    CacheQuestion.set(result)
    console.log(result)
    navigator.navigateBack()
}
onMounted(() => {
    fetchData().then(ret => {
        console.log(ret)
        questions.value = Array.from(new Set([...CacheQuestion.get(), ...(ret || [])]))
    }).catch(e =>{
        questions.value = CacheQuestion.get()
    })
    
})

</script>

<style scoped lang="scss">
.question {
    padding: 16px;
    &__item {
        display: flex;
        flex-direction: row;
        align-items: center;
        margin-bottom: 16px;
    }
    &__del {
        font-size: 14px;
        color: $uni-color-error;
        font-weight: 500;
        padding-left: 12px;
    }
    &__button {
        padding: 8px 16px;
        border: solid 1px $uni-text-color-disable;
        color: $uni-text-color;
        text-align: center;
        font-size: 14px;
        border-radius: 8px;
    }
    &__save {
        margin-top: 16px;
        background-color: $uni-color-primary;
        color: white;
    }
    &__input {
        flex: 1;
        padding: 8px 16px;
        border: 1px solid #e8e8e8;
        border-radius: 8px;
        font-size: 14px;
    }
}
</style>